﻿
using System.Collections.Generic;
using System;
using BCService.Utils;
using BCCommon;
using BCData.TMS.TransportSpecificServiceConfig;
using BCDto.TMS.TransportSpecificServiceConfig;
using BCEntity.TMS.TransportSpecificServiceConfig;
using BCDto.Sim.Admin.Admin;
using BCEntity.TMS.TransportSpecificServiceConfigOverWrite;
using BCEntity.Common.EntityNameConst;
using BCData.TMS.TransportSpecificServiceConfigOverWrite;
using BCData.TMS.Agent.AgentRecord;
using BCDto.TMS.FreightContact;
using BCDto.Website.User;
using BCData.TMS.Agent.AgentAreaRecord;
using BCService.Common.Area;
using System.Linq;
using BCDto.TMS.TransportSpecificServiceConfigOverWrite;

namespace BCService.TMS.TransportSpecificServiceConfigOverWrite
{
    public class TransportSpecificServiceConfigOverWriteService : ITransportSpecificServiceConfigOverWriteService
    {
        #region var
        private readonly IDatabaseContext databaseContext;
        private ITransportSpecificServiceConfigData transportSpecificServiceConfigData;
        private ITransportSpecificServiceConfigOverWriteData transportSpecificServiceConfigOverWriteData;
        private readonly IAgentRecordData agentRecordData;
        private readonly IAgentAreaRecordData agentAreaRecordData;
        private readonly IRedisService redisService;
        private readonly IZoneService zoneService;

        private readonly string key = string.Format("{0}", EntityNameConst.TransportSpecificServiceConfigEntity);
        private readonly string keyView = string.Format("{0}", EntityNameConst.TransportSpecificServiceConfigViewEntity);

        #endregion

        #region 构造函数


        public TransportSpecificServiceConfigOverWriteService(IDatabaseContext databaseContext, ITransportSpecificServiceConfigData transportSpecificServiceConfigData, ITransportSpecificServiceConfigOverWriteData transportSpecificServiceConfigOverWriteData, IAgentRecordData agentRecordData, IRedisService redisService, IAgentAreaRecordData agentAreaRecordData,
            IZoneService zoneService)
        {
            this.databaseContext = databaseContext;
            this.transportSpecificServiceConfigData = transportSpecificServiceConfigData;
            this.transportSpecificServiceConfigOverWriteData = transportSpecificServiceConfigOverWriteData;
            this.agentRecordData = agentRecordData;
            this.redisService = redisService;
            this.agentAreaRecordData = agentAreaRecordData;
            this.zoneService = zoneService;
        }
        #endregion


        #region Add
        /// <summary>
        /// 添加新运输特殊服务费配置纪录
        /// </summary>
        /// <param name="transportSpecificServiceConfigOverWriteRequestDto"></param>
        /// <param name="admin"></param>
        /// <returns></returns>
        public TransportSpecificServiceConfigOverWriteDto Add(TransportSpecificServiceConfigOverWriteRequestDto transportSpecificServiceConfigOverWriteRequestDto, AdminDto admin)
        {
            if (admin.CompanyId == 1)
            {
                throw new ArgumentException("代理商专用接口");
            }
            else
            {
                var agentRecord = this.agentRecordData.GetEntityByCompanyId(admin.CompanyId).Result;
                if (agentRecord == null)
                {
                    throw new ArgumentException("您不归属任何代理商，暂无权限添加");
                }
                if (string.IsNullOrWhiteSpace(transportSpecificServiceConfigOverWriteRequestDto.CountyCode))
                {
                    throw new ArgumentNullException("CountyCode");
                }

                var zoneEntity = this.zoneService.GetFromZoneEntity(transportSpecificServiceConfigOverWriteRequestDto.CountyCode);
                if (zoneEntity == null || zoneEntity.countyEntity == null)
                {
                    throw new ArgumentException("区县编码不存在!");
                }
                //添加 
                var baseEntity = transportSpecificServiceConfigData.GetEntityAsync(transportSpecificServiceConfigOverWriteRequestDto.TransportSpecificServiceConfigId).GetAwaiter().GetResult();
                if (baseEntity == null)
                {
                    throw new ArgumentException("TransportSpecificServiceConfigId基础表中查不到!");
                }

                int count = transportSpecificServiceConfigOverWriteData.GetCountAsync(baseEntity.VehicleTypeId,zoneEntity.provinceEntity.ProvinceCode, zoneEntity.cityEntity.CityCode, transportSpecificServiceConfigOverWriteRequestDto.CountyCode, agentRecord.AgentRecordId, transportSpecificServiceConfigOverWriteRequestDto.TransportSpecificServiceConfigId).GetAwaiter().GetResult();
                if (count > 0)
                {
                    throw new Exception("正在添加重复的记录!出现这种异常,请联系开发人员!");
                }
                //添加
                return this.transportSpecificServiceConfigOverWriteData.InsertAsync(new TransportSpecificServiceConfigOverWriteEntity()
                {
                    VehicleTypeId = baseEntity.VehicleTypeId,
                    VehicleTypeName = baseEntity.VehicleTypeName,
                    SpecificServiceType = transportSpecificServiceConfigOverWriteRequestDto.SpecificServiceType,
                    ServiceTitle = transportSpecificServiceConfigOverWriteRequestDto.ServiceTitle,
                    HasRemark = transportSpecificServiceConfigOverWriteRequestDto.HasRemark,
                    ServiceRemark = transportSpecificServiceConfigOverWriteRequestDto.ServiceRemark,
                    ServiceAmount = transportSpecificServiceConfigOverWriteRequestDto.ServiceAmount,
                    HasUnit = transportSpecificServiceConfigOverWriteRequestDto.HasUnit,
                    ServiceUnit = transportSpecificServiceConfigOverWriteRequestDto.ServiceUnit,
                    Enabled = transportSpecificServiceConfigOverWriteRequestDto.Enabled,
                    ShortName = transportSpecificServiceConfigOverWriteRequestDto.ShortName,

                    ProvinceCode = zoneEntity.provinceEntity.ProvinceCode,
                    CityCode = zoneEntity.cityEntity.CityCode,
                    CountyCode = transportSpecificServiceConfigOverWriteRequestDto.CountyCode,

                    AgentRecordId = agentRecord.AgentRecordId,
                    TransportSpecificServiceConfigId = transportSpecificServiceConfigOverWriteRequestDto.TransportSpecificServiceConfigId,

                    CreateAdminId = admin.AdminId,
                    CreateAdminName = admin.FullName,
                    CreateTime = DateTime.Now,
                    EditAdminId = admin.AdminId,
                    EditAdminName = admin.FullName,
                    UpdateTime = DateTime.Now,
                }).GetAwaiter().GetResult().As<TransportSpecificServiceConfigOverWriteDto>();

            }
        }
        #endregion


        #region update
        /// <summary>
        /// 修改运输特殊服务费配置记录
        /// </summary>
        /// <param name="transportSpecificServiceConfigOverWritePutDto"></param>
        /// <param name="admin"></param>
        /// <returns></returns>
        public TransportSpecificServiceConfigOverWriteDto Update(TransportSpecificServiceConfigOverWritePutDto transportSpecificServiceConfigOverWritePutDto, AdminDto admin)
        {
            if (admin.AdminId == 1)
            {
                throw new ArgumentException("代理商专用接口");
            }
            else
            {
                var agentRecord = this.agentRecordData.GetEntityByCompanyId(admin.CompanyId).Result;
                if (agentRecord == null)
                {
                    throw new ArgumentException("您不归属任何代理商，暂无权限添加");
                }

                //修改
                var org = transportSpecificServiceConfigOverWriteData.GetEntityAsync(transportSpecificServiceConfigOverWritePutDto.TransportSpecificServiceConfigOverwriteId).GetAwaiter().GetResult() ?? throw new ArgumentException("找不到要修改的记录!");

                org.SpecificServiceType = transportSpecificServiceConfigOverWritePutDto.SpecificServiceType;
                org.ServiceTitle = transportSpecificServiceConfigOverWritePutDto.ServiceTitle;
                org.ShortName = transportSpecificServiceConfigOverWritePutDto.ShortName;
                org.HasRemark = transportSpecificServiceConfigOverWritePutDto.HasRemark;
                org.ServiceRemark = transportSpecificServiceConfigOverWritePutDto.ServiceRemark;
                org.ServiceAmount = transportSpecificServiceConfigOverWritePutDto.ServiceAmount;
                org.HasUnit = transportSpecificServiceConfigOverWritePutDto.HasUnit;
                org.ServiceUnit = transportSpecificServiceConfigOverWritePutDto.ServiceUnit;
                org.Enabled = transportSpecificServiceConfigOverWritePutDto.Enabled;

                org.UpdateTime = DateTime.Now;
                org.EditAdminId = admin.AdminId;
                org.EditAdminName = admin.FullName;

                this.redisService.DeleteMultipleKey(keyView, false);
                return transportSpecificServiceConfigOverWriteData.UpdateAsync(org).GetAwaiter().GetResult().As<TransportSpecificServiceConfigOverWriteDto>();
            }
        }
        #endregion

        #region 重写开启关闭
        public TransportSpecificServiceConfigOverWriteDto UpdateEnable(AdminDto admin, long transportSpecificServiceConfigOverWriteId, bool enabled)
        {

            if (admin.AdminId == 1)
            {
                throw new ArgumentException("代理商专用接口");
            }
            else
            {
                var entity = transportSpecificServiceConfigOverWriteData.GetEntityAsync(transportSpecificServiceConfigOverWriteId).GetAwaiter().GetResult() ?? throw new ArgumentException("找不到要修改的记录!");

                entity.Enabled = enabled;
                entity.UpdateTime = DateTime.Now;
                entity.EditAdminId = admin.AdminId;
                entity.EditAdminName = admin.FullName;

                this.redisService.DeleteMultipleKey(keyView, false);
                return transportSpecificServiceConfigOverWriteData.UpdateAsync(entity).GetAwaiter().GetResult().As<TransportSpecificServiceConfigOverWriteDto>();
            }
        }
        #endregion


        #region GetList  获取运输特殊服务费配置记录--[分页]
        public PageableList<TransportSpecificServiceConfigViewDto> GetList(AdminDto admin, int? vehicleTypeId, string specificServiceType, string serviceTitle, string provinceCode, string cityCode, string countyCode, int pageIndex, int pageSize)
        {
            if (admin.CompanyId == 1)
            {
                throw new ArgumentException("代理商专用接口");
            }
            else
            {
                var agentRecord = this.agentRecordData.GetEntityByCompanyId(admin.CompanyId).Result;
                if (agentRecord == null)
                {
                    throw new ArgumentException("您不归属任何代理商，暂无权限添加");
                }
                string cacheKey = this.redisService.GetKey(keyView,vehicleTypeId, provinceCode, cityCode, countyCode, agentRecord.AgentRecordId, pageIndex, pageSize);
                var result = redisService.TryGet(cacheKey, () =>
                {
                    int fCount = 0;
                    IEnumerable<TransportSpecificServiceConfigOverWriteEntity> flist;
                    (flist, fCount) = transportSpecificServiceConfigOverWriteData.GetListAsync(vehicleTypeId,specificServiceType, serviceTitle, provinceCode, cityCode, countyCode, agentRecord.AgentRecordId, pageIndex, pageSize).GetAwaiter().GetResult();

                    return new PageableList<TransportSpecificServiceConfigViewDto>()
                    {
                        Count = fCount,
                        Items = flist.As<IEnumerable<TransportSpecificServiceConfigViewDto>>(),
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        ServerTime = DateTime.Now,
                    };
                }, TimeSpan.FromMinutes(30));
                return result;
            }
        }
        #endregion

        #region GetListBase
        public PageableList<TransportSpecificServiceConfigDto> GetListBase(int? vehicleTypeId,string specificServiceType, string serviceTitle,int pageIndex, int pageSize)
        {
            int fCount = 0;
            IEnumerable<TransportSpecificServiceConfigEntity> fList;
            string cacheKey = this.redisService.GetKey(key, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                (fList, fCount) = transportSpecificServiceConfigData.GetListAsync(vehicleTypeId,specificServiceType,serviceTitle, pageIndex, pageSize).GetAwaiter().GetResult();

                return new PageableList<TransportSpecificServiceConfigDto>()
                {
                    Count = fCount,
                    Items = fList.As<IEnumerable<TransportSpecificServiceConfigDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now,
                };
            }, TimeSpan.FromMinutes(30));
            return result;
        }
        #endregion


        #region GetOnlyList  获取运输特殊服务费配置记录 无分页
        public List<TransportSpecificServiceConfigViewDto> GetOnlyList(long agentRecordId, int? vehicleTypeId, string specificServiceType, string serviceTitle, string countyCode)
        {
            if (string.IsNullOrWhiteSpace(countyCode))
            {
                throw new ArgumentNullException("CountyCode");
            }

            string cacheKey = this.redisService.GetKey(keyView, vehicleTypeId, specificServiceType, serviceTitle, countyCode, agentRecordId);
            var result = redisService.TryGet(cacheKey, () =>
            {
                return transportSpecificServiceConfigOverWriteData.GetOnlyListAsync(vehicleTypeId,specificServiceType, serviceTitle, null, null, countyCode, agentRecordId).GetAwaiter().GetResult().As<IEnumerable<TransportSpecificServiceConfigViewDto>>().ToList();
            }, TimeSpan.FromMinutes(30));
            return result;
        }

        public List<TransportSpecificServiceConfigViewDto> GetOnlyListBase(int? vehicleTypeId,string specificServiceType, string serviceTitle)
        {
            string cacheKey = this.redisService.GetKey(keyView,vehicleTypeId, specificServiceType, serviceTitle);
            var result = redisService.TryGet(cacheKey, () =>
            {
                return transportSpecificServiceConfigData.GetOnlyListAsync(vehicleTypeId, specificServiceType, serviceTitle).GetAwaiter().GetResult().As<IEnumerable<TransportSpecificServiceConfigViewDto>>().ToList();
            }, TimeSpan.FromMinutes(30));
            return result;
        }

        #endregion


        #region 获取运输特殊服务配置记录
        public TransportSpecificServiceConfigDto GetById(int transportSpecificServiceConfigOverWriteId)
        {
            string cacheKey = this.redisService.GetKey(keyView, transportSpecificServiceConfigOverWriteId);
            var result = redisService.TryGet(cacheKey, () =>
            {
                return this.transportSpecificServiceConfigOverWriteData.GetEntityAsync(transportSpecificServiceConfigOverWriteId).GetAwaiter().GetResult().As<TransportSpecificServiceConfigDto>();
            }, TimeSpan.FromDays(1));
            return result;
        }
        #endregion

    }
}